package com.petvc.tv

import android.content.Intent
import android.os.Bundle
import android.view.Window
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.foundation.Image
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.platform.LocalContext
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.launch
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import org.json.JSONObject
import android.os.Handler
import android.os.Looper
import android.content.Context
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.suspendCancellableCoroutine
import java.net.Socket

private fun getUserIdFromToken(accessToken: String): String? {
    return try {
        val parts = accessToken.split(".")
        if (parts.size != 3) return null
        val payload = android.util.Base64.decode(parts[1], android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING)
        val json = org.json.JSONObject(String(payload))
        json.optString("user_id", null)
    } catch (e: Exception) {
        null
    }
}

class LoginActivity : ComponentActivity() {
    companion object {
        private var currentInstance: LoginActivity? = null
        fun getCurrentInstance(): LoginActivity? = currentInstance
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        currentInstance = this
        setContent {
            PetTVTheme {
                LoginScreen()
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        currentInstance = null
    }

    suspend fun registerDevice(context: Context, deviceName: String, deviceType: String): Pair<Int, String> {
        val userData = AuthService.getCurrentUser(context) ?: return Pair(-1, "")
        val accessToken = userData.accessToken
        val deviceId = DeviceUtils.getDeviceId(context)
        val ipAddress = DeviceUtils.getLocalIpAddress() ?: ""
        val deviceMac = DeviceUtils.getMacAddress() ?: ""
        val url = ApiConfig.Device.ADD
        val json = org.json.JSONObject().apply {
            put("name", deviceName)
            put("type", deviceType)
            put("device_id", deviceId)
            put("device_name", deviceName)
            put("ip_address", ipAddress)
            put("device_mac", deviceMac)
        }
        val headers = mapOf("Authorization" to "Bearer $accessToken")
        val response = NetworkUtils.postRequest(url, json.toString(), headers)
        android.util.Log.d("PetTV", "[HTTP] 设备注册响应: code=${response.statusCode}, message=${response.message}")
        return Pair(response.statusCode, response.message ?: "")
    }

    fun connectAndRegisterDevice(context: Context) {
        HeartbeatManager.connectAndRegisterDevice(context)
    }

    fun stopHeartbeat() {
        HeartbeatManager.stopHeartbeat()
    }

    suspend fun performLogin(
        context: Context,
        username: String,
        password: String
    ): Pair<Boolean, String> {
        LogUtils.logDebug("开始执行登录操作: 用户=$username")
        return try {
            val result = AuthService.login(context, username, password)
            LogUtils.logDebug("登录操作完成: 成功=${result.success}, 消息=${result.message}")
            Pair(result.success, result.message)
        } catch (e: Exception) {
            LogUtils.logDebug("登录操作异常: ${e.message}")
            Pair(false, "登录失败: ${e.message}")
        }
    }
}

@Preview
@Composable
fun LoginScreen() {
    val primaryColor = Color(0xFFFF6B35)
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var isPasswordVisible by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(false) }
    val focusManager = LocalFocusManager.current
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()

    // 背景
    Box(
        modifier = Modifier
            .fillMaxSize()
            .pointerInteropFilter {
                if (it.action == android.view.MotionEvent.ACTION_DOWN) {
                    focusManager.clearFocus()
                }
                false
            }
    ) {
        // 背景图片
        Image(
            painter = painterResource(id = R.drawable.login_bg),
            contentDescription = null,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop
        )
        // 登录容器
        Box(
            modifier = Modifier
                .align(Alignment.Center)
                .width(360.dp)
                .shadow(16.dp, RoundedCornerShape(24.dp))
                .background(Color.White.copy(alpha = 0.95f), RoundedCornerShape(24.dp))
                .border(1.dp, primaryColor.copy(alpha = 0.1f), RoundedCornerShape(24.dp))
                .padding(32.dp)
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 标题
                Text(
                    text = "PetTV",
                    fontSize = 48.sp,
                    color = primaryColor,
                    fontFamily = FontFamily.Cursive,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = 12.dp)
                )
                Text(
                    text = "欢迎来到宠物视频天地",
                    color = Color(0xFF757575),
                    fontSize = 20.sp,
                    modifier = Modifier.padding(bottom = 32.dp)
                )
                // 用户名输入框
                OutlinedTextField(
                    value = username,
                    onValueChange = { username = it },
                    placeholder = { Text("请输入用户名", fontSize = 18.sp) },
                    leadingIcon = {
                        Icon(Icons.Filled.Person, contentDescription = null, tint = Color(0xFFBDBDBD), modifier = Modifier.size(28.dp))
                    },
                    singleLine = true,
                    shape = RoundedCornerShape(16.dp),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp),
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = primaryColor,
                        unfocusedBorderColor = Color(0xFFEEEEEE),
                        focusedLabelColor = primaryColor
                    ),
                    textStyle = LocalTextStyle.current.copy(fontSize = 18.sp),
                    keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                        keyboardType = KeyboardType.Text,
                        imeAction = ImeAction.Next
                    ),
                    enabled = !isLoading
                )
                // 密码输入框
                OutlinedTextField(
                    value = password,
                    onValueChange = { password = it },
                    placeholder = { Text("请输入密码", fontSize = 18.sp) },
                    leadingIcon = {
                        Icon(Icons.Filled.Lock, contentDescription = null, tint = Color(0xFFBDBDBD), modifier = Modifier.size(28.dp))
                    },
                    trailingIcon = {
                        IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) {
                            Icon(
                                if (isPasswordVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff,
                                contentDescription = if (isPasswordVisible) "隐藏密码" else "显示密码",
                                tint = Color(0xFFBDBDBD)
                            )
                        }
                    },
                    singleLine = true,
                    shape = RoundedCornerShape(16.dp),
                    visualTransformation = if (isPasswordVisible) androidx.compose.ui.text.input.VisualTransformation.None else PasswordVisualTransformation(),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp),
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = primaryColor,
                        unfocusedBorderColor = Color(0xFFEEEEEE),
                        focusedLabelColor = primaryColor
                    ),
                    textStyle = LocalTextStyle.current.copy(fontSize = 18.sp),
                    keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                        keyboardType = KeyboardType.Password,
                        imeAction = ImeAction.Done
                    ),
                    enabled = !isLoading
                )
                // 登录按钮
                Button(
                    onClick = {
                        if (!isLoading) {
                            isLoading = true
                            coroutineScope.launch {
                                val (success, loginMsg) = (context as LoginActivity).performLogin(context, username, password)
                                isLoading = false
                                if (success) {
                                    val (statusCode, message) = (context as LoginActivity).registerDevice(context, DeviceUtils.getDeviceName(), "TV")
                                    when (statusCode) {
                                        201 -> {
                                            ToastUtils.showLoginMessage(context, "设备注册成功")
                                            (context as? LoginActivity)?.connectAndRegisterDevice(context)
                                            val intent = Intent(context, PlayerActivity::class.java)
                                            context.startActivity(intent)
                                            (context as? ComponentActivity)?.finish()
                                        }
                                        409 -> {
                                            ToastUtils.showLoginMessage(context, "设备验证成功")
                                            (context as? LoginActivity)?.connectAndRegisterDevice(context)
                                            val intent = Intent(context, PlayerActivity::class.java)
                                            context.startActivity(intent)
                                            (context as? ComponentActivity)?.finish()
                                        }
                                        else -> {
                                            android.util.Log.e("PetTV", "[HTTP] 设备注册失败")
                                            ToastUtils.showLoginMessage(context, "设备注册失败")
                                        }
                                    }
                                } else {
                                    ToastUtils.showLoginMessage(context, loginMsg)
                                }
                            }
                        }
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp)
                        .height(56.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = primaryColor
                    ),
                    enabled = !isLoading
                ) {
                    if (isLoading) {
                        CircularProgressIndicator(
                            color = Color.White,
                            modifier = Modifier.size(24.dp)
                        )
                    } else {
                        Text("登 录", fontSize = 22.sp, fontWeight = FontWeight.Medium)
                    }
                }
            }
        }
    }
} 